package sz.szsmk.citizencard.mvp.dzsmkpresenter;

import android.app.Service;
import android.os.Handler;
import android.os.Vibrator;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import rx.functions.Action1;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.db.DaoSession;
import sz.szsmk.citizencard.db.MyQrCodeNumberDao;
import sz.szsmk.citizencard.db.SysConfDao;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.request.AdvertisementsReq;
import sz.szsmk.citizencard.model.network.bean.request.IsAcardReq;
import sz.szsmk.citizencard.model.network.bean.response.AdvertisementsRes;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.QrCodeNumberRequest;
import sz.szsmk.citizencard.model.network.dzbean.res.GetUserInfoRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MyQrCodeNumber;
import sz.szsmk.citizencard.model.network.dzbean.res.QrCodeNumber;
import sz.szsmk.citizencard.model.network.dzbean.res.QrCodeNumberResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QrNumberResponse;
import sz.szsmk.citizencard.model.network.dzbean.res.SysConf;
import sz.szsmk.citizencard.model.network.dzbean.res.User;
import sz.szsmk.citizencard.mvp.MainFragmentMvpView;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.HttpApi;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.util.CommonUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.util.SecureSharedPreferences;

/**
 * Created by chensf on 17/10/1.
 */

public class MainFragmentPresenter extends AppBasePresenter<MainFragmentMvpView> {

    @Inject
    NetworkDateSource mNetworkDateSource;

    private Handler mHandler;

    private boolean pauseRefresh = true;
    private boolean needRefreshCode = false;


    private NetworkDateSources mNetworkDate;
    private Vibrator mVibrator;
    private int qrImgRefreshTime = 60;
    private int qrAvaliTime = 60; //二维码有效时间S

    @Inject
    public MainFragmentPresenter() {
        getComponent().inject(this);
        this.mNetworkDate = NetworkDateSources.getInstance();
        mHandler = new Handler();

    }

    public void getQrNumber() {
        checkViewAttached();
        mVibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);

        final String lnt = "";
        final String lat = "";
        pauseRefresh = false;
        QrCodeNumberResult qcr = null;
        DaoSession daoSession = DaggerApplication.getmDaoSession();
        SysConfDao sysConfDao = daoSession.getSysConfDao();
        final MyQrCodeNumberDao myQrCodeNumberDao = daoSession.getMyQrCodeNumberDao();

        int offlineCount = 0; //离线生产个数
        List<SysConf> sysConfs = sysConfDao.loadAll();
        if (null != sysConfs && sysConfs.size() > 0) {
            SysConf sysConf = sysConfs.get(0);
            offlineCount = sysConf.getOfflineCount();
            qrAvaliTime = sysConf.getQrAvaliTime();
            qrImgRefreshTime = sysConf.getQrImgRefreshTime();
        }
        //qrImgRefreshTime = 10;
        //qrAvaliTime = 10;
        boolean hasNetwork = CommonUtils.hasNetwork(getActivity());
        needRefreshCode = false;

        List<MyQrCodeNumber> myQrCodeNumbers = myQrCodeNumberDao.loadAll();
        for (MyQrCodeNumber myQrCodeNumber : myQrCodeNumbers) {
            //有1秒的冗余，若快1秒就到期了，也认为是过期了
            if (System.currentTimeMillis() > myQrCodeNumber.getExpireTime() - 1000) {
                myQrCodeNumberDao.delete(myQrCodeNumber);
            }
        }
        //loadAll不会返回个null
        List<MyQrCodeNumber> myQrCodeNumbersUsables = myQrCodeNumberDao.loadAll();
        int hasQrCodeCount = myQrCodeNumbersUsables.size(); //还有多少个有效的二维码

        if (!hasNetwork) { //没有网络
            if (hasQrCodeCount > 0) {
                MyQrCodeNumber myQrCodeNumber = myQrCodeNumbersUsables.get(0);
                qcr = new QrCodeNumberResult();
                qcr.setResultCode(Constant.QUERY_QR_RESULT_AUTHED);
                qcr.setQrCode(myQrCodeNumber.getQrNumber());
                getMvpView().onGainQrCodeNumber(qcr);
                needRefreshCode = true;
            } else { //若没有二维码，可能是未实名或实名完了所有的码都过期了，反正就是要提示用户要去连网
                getMvpView().onNoQrCodeUsed();
            }
            handlerRefreshAndVibrator(qrImgRefreshTime);
        } else {
            //需要向网络请求多少个二维码
            int needQrCode = (offlineCount - hasQrCodeCount) + 1;
            //qcr = mokeQrCodeNumberResult();

            QrCodeNumberRequest qrr = new QrCodeNumberRequest();
            qrr.setCount(needQrCode + "");
            String longitude = SecureSharedPreferences.getString(Constant.LONGITUDE);
            String latitude = SecureSharedPreferences.getString(Constant.LATITUDE);
            qrr.setLnt(longitude);
            qrr.setLat(latitude);

            ObjectSignatureUtil.signatureRequest(qrr);
            String json = new Gson().toJson(qrr);
            L.e(Constant.TAG,"二维码入参-------"+json);
            mNetworkDateSource.getQrNumber(qrr, new Action1<QrNumberResponse>() {
                @Override
                public void call(QrNumberResponse qrNumberResponse) {
                    String code = qrNumberResponse.getCode();
                    if (code.equals("0000")) {
                        QrNumberResponse.DataBean data = qrNumberResponse.getData();
                        String json = new Gson().toJson(data);
                        QrCodeNumberResult qrr = new Gson().fromJson(json, QrCodeNumberResult.class);

                        if (data == null) {
                            return;
                        }

                        if (Constant.QUERY_QR_RESULT_AUTHED.equals(qrr.getResultCode())) {
                            ArrayList<QrCodeNumber> qrList = (ArrayList<QrCodeNumber>) qrr.getQrList();
//                            List<QrCodeNumber> qrList = data.getQrList();

                            List<String> qrString = new ArrayList<String>();
                            for (QrCodeNumber qrCodeNumber : qrList) {
                                qrString.add(qrCodeNumber.getQrString());
                            }

                            if (null != qrString && qrString.size() > 1) { //若是大于一个，则多余的则存在数据库
                                for (int i = 1; i < qrString.size(); i++) {
                                    String qrCode = qrString.get(i);
                                    long expireTime = System.currentTimeMillis() + qrAvaliTime * 1000;

                                    MyQrCodeNumber myQrCodeNumber = new MyQrCodeNumber();
                                    myQrCodeNumber.setExpireTime(expireTime);
                                    myQrCodeNumber.setQrNumber(qrCode);
                                    myQrCodeNumberDao.insert(myQrCodeNumber);
                                }
                            }

                            Collections.shuffle(qrString); //测试，随便一个数出来看看
                            if (null != qrString && qrString.size() > 0) {
                                qrr.setQrCode(qrString.get(0)); //展示的码
                                needRefreshCode = true; //是需要刷新code的
                            }
                            handlerRefreshAndVibrator(qrImgRefreshTime);
                        }
                        if (getMvpView() != null) {
                            getMvpView().onGainQrCodeNumber(qrr);
                        }

                    } else {
                        getMvpView().onGainQrCodeException();
                    }
                }
            }, new ErrorAction() {
                @Override
                public void onCall(Throwable throwable) {

                }
            });

        }


    }


    public void getPersonInfo() {
        checkViewAttached();
        HttpApi httpApi = mNetworkDateSource.getHttpApi();
        CommonRequest commonRequest = ObjectSignatureUtil.getCommonRequest();

//
//        httpApi.getUserInfo(commonRequest).compose(RxNetworkHelp.<User>handleResult()).subscribe(new RxSubscribe<User>(getActivity()) {
//            @Override
//            protected void onOk(User response) {
//                getMvpView().onGainPersonInfo(response);
//            }
//        });
//
        mNetworkDateSource.getUserInfo(commonRequest, new Action1<GetUserInfoRes>() {
            @Override
            public void call(GetUserInfoRes baseRes) {
                String code = baseRes.getCode();
                if (code.equals("0000")) {
                    Object data = baseRes.getData();
                    String json = new Gson().toJson(data);
                    User user = new Gson().fromJson(json, User.class);
                    String idCardNumber = user.getIdCardNumber();
//                    ACache.get(DaggerApplication.getIns()).put("userIdCard", idCardNumber);
                    getACard(idCardNumber);
//                    getMvpView().onGainPersonInfo(user);
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });


    }

    public void getACard(String idCardNumber) {
        IsAcardReq isAcardReq = new IsAcardReq();

//        String userIdCard = ACache.get(DaggerApplication.getIns()).getAsString("userIdCard");
//        L.e(Constant.MTAG, "用户身份证：" + userIdCard);
        isAcardReq.setPapaer_no(idCardNumber);
        mNetworkDate.getACard(isAcardReq, new SubscribeResult<BaseBean>() {
            @Override
            protected void onOk(BaseBean response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "电子市民卡查询A卡：" + json);
                getMvpView().getAcardSucc(response);
            }

            @Override
            protected void onFailure(BaseBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    private void handlerRefreshAndVibrator(int qrImgRefreshTime) {
        if (needRefreshCode) { //若需要刷新，则在这里计时
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自刷新
                    if (!pauseRefresh) {
                        //L.e(System.currentTimeMillis()+"---------------------------postDelayed里，马上刷新 "+pauseRefresh);

                        getQrNumber();
                    } else {
                        //L.e(System.currentTimeMillis()+"---------------------------postDelayed里，但不会去刷新 "+pauseRefresh);

                        //暂停了
                    }
                }
            }, qrImgRefreshTime * 1000);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自刷新
                    if (!pauseRefresh) {
                        L.e(System.currentTimeMillis() + "---------------------------处理handlerVibrator ");
                        //振动
                        handlerVibrator();
                    }
                }
            }, qrImgRefreshTime * 1000 - 5000);
        }
    }

    private void handlerVibrator() {
        mVibrator.vibrate(1000); //直接振动1秒
        //mVibrator.vibrate(new long[]{1000, 1000}, -1);
    }

    public boolean isShowingCode() {
        return needRefreshCode & !pauseRefresh;
    }

    public void setPauseRefresh(boolean pauseRefresh) {
        if (!pauseRefresh) {
            //L.e(System.currentTimeMillis()+"---------------------------setPauseRefresh  resumeStatus去 pauseRefresh:"+pauseRefresh);
            resumeStatus();
        } else {//不会去刷新显示的
            //L.e(System.currentTimeMillis()+"---------------------------setPauseRefresh 没resumeStatus去 pauseRefresh:"+pauseRefresh);
            if (null != mVibrator) {
                mVibrator.cancel();
            }
            this.pauseRefresh = pauseRefresh;
        }
    }

    public void forceRefresh() {
        mHandler.removeCallbacksAndMessages(null);
        getQrNumber();
    }

    public void resumeStatus() {
        //若是暂停了，需要考虑所有正在执行的任务,或在队列中有延迟的任务
        if (pauseRefresh && needRefreshCode) { //若需要刷新，则在这里计时
            //L.e(System.currentTimeMillis()+"---------------------------resumeStatus了呢  pauseRefresh:"+pauseRefresh);
            mHandler.removeCallbacksAndMessages(null);
            getQrNumber();
        } else { //不会去刷新显示的
            if (null != mVibrator) {
                mVibrator.cancel();
            }
            //L.e(System.currentTimeMillis()+"---------------------------resumeStatus，但失败  pauseRefresh:"+pauseRefresh);
        }
        pauseRefresh = false;

    }

    @Override
    public void detachView() {
        super.detachView();
        if (null != mVibrator) {//不会去刷新显示的
            mVibrator.cancel();
        }
        pauseRefresh = true;
        mHandler.removeCallbacksAndMessages(null);
    }

    public void getAdvertisements(){
        AdvertisementsReq advertisementsReq = new AdvertisementsReq();
        advertisementsReq.setAdArea("1");

        mNetworkDateSource.getAdvertisements( advertisementsReq, baseRes -> {
            String code = baseRes.getCode();
            if (code.equals("0000")) {
                getMvpView().getAdvertisementsResult(baseRes);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }
}
